package io.renren.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;

import org.apache.commons.lang.StringUtils;

import org.springframework.stereotype.Controller;

import io.renren.dao.xtd.DataContractDaoXtd;
import io.renren.entity.DataContractEntity;
import io.renren.entity.DataPayrollEntity;
import io.renren.entity.DictDepartmentEntity;
import io.renren.entity.xtd.DataContractEntityXtd;
import io.renren.entity.xtd.DataContractpayDetailEntityXtd;
import io.renren.entity.xtd.DataContractpayEntityXtd;
import io.renren.entity.xtd.DictDepartmentEntityXtd;
import io.renren.entity.xtd.DictEmployeeEntityXtd;
import io.renren.entity.xtd.HisContractEntityXtd;
import io.renren.entity.xtd.HisContractpayEntityXtd;
import io.renren.service.DataCalculateKService;
import io.renren.service.DataContractService;
import io.renren.service.DataDxRecordService;
import io.renren.service.DataEmpPerformanceService;
import io.renren.service.DataPayrollDxdetailService;
import io.renren.service.DictDepartmentService;
import io.renren.service.DictEmployeeService;
import io.renren.service.SysConfigService;
import io.renren.service.SysWorkLogService;
import io.renren.service.xtd.DataAddmoneyServiceXtd;
import io.renren.service.xtd.DataAreaachiRecordServiceXtd;
import io.renren.service.xtd.DataAreacheckServiceXtd;
import io.renren.service.xtd.DataBigareaachiRecordServiceXtd;
import io.renren.service.xtd.DataBigareacheckServiceXtd;
import io.renren.service.xtd.DataBranchachiRecordServiceXtd;
import io.renren.service.xtd.DataBranchcheckServiceXtd;
import io.renren.service.xtd.DataContractServiceXtd;
import io.renren.service.xtd.DataContractXtdServiceXtd;
import io.renren.service.xtd.DataContractpayDetailServiceXtd;
import io.renren.service.xtd.DataContractpayServiceXtd;
import io.renren.service.xtd.DataDirectcheckServiceXtd;
import io.renren.service.xtd.DataDirectorachiRecordServiceXtd;
import io.renren.service.xtd.DataEmployeeachiRecordServiceXtd;
import io.renren.service.xtd.DataFormalcheckServiceXtd;
import io.renren.service.xtd.DataLostmoneyServiceXtd;
import io.renren.service.xtd.DataMonthdirectServiceXtd;
import io.renren.service.xtd.DataPayrollDxdetailServiceXtd;
import io.renren.service.xtd.DataPayrollServiceXtd;
import io.renren.service.xtd.DataRecommendRecordServiceXtd;
import io.renren.service.xtd.DataRecommendServiceXtd;
import io.renren.service.xtd.DataTeampayServiceXtd;
import io.renren.service.xtd.DictDepartmentServiceXtd;
import io.renren.service.xtd.DictEmployeeServiceXtd;
import io.renren.service.xtd.DictJobServiceXtd;
import io.renren.service.xtd.DictWagesTypeServiceXtd;
import io.renren.service.xtd.HisContractServiceXtd;
import io.renren.service.xtd.HisContractpayServiceXtd;
import io.renren.service.xtd.HisDepartmentServiceXtd;
import io.renren.service.xtd.HisEmployeeServiceXtd;
import io.renren.service.xtd.impl.DataTeampayServiceImplXtd;
import io.renren.utils.AssignUtils;
import io.renren.utils.CalculateUtils;
import io.renren.utils.Common;
import io.renren.utils.ExcelUtils;
import io.renren.utils.PageUtils;
import io.renren.utils.R;
import io.renren.utils.ShiroUtils;

/**
 * 历史合同基础表
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2018-05-31 15:37:38
 * @date 2018-05-31 13:49:46
 */
@Controller
@RequestMapping("datacontract")
public class DataContractController {
	@Autowired
	private HisContractpayServiceXtd hisContractpayServiceXtd;
	@Autowired
	private HisContractServiceXtd hisContractServiceXtd;
	@Autowired
	private SysWorkLogService sysWorkLogService;
	@Autowired
	private DataContractXtdServiceXtd dataContractXtdServiceXtd;
	@Autowired
	private DataBranchachiRecordServiceXtd dataBranchachiRecordServiceXtd;
	@Autowired
	private DataContractpayServiceXtd dataContractpayServiceXtd;
	@Autowired
	private HisEmployeeServiceXtd hisEmployeeServiceXtd;
	@Autowired
	private DictDepartmentService dictDepartmentService;
	@Autowired
	private DataContractServiceXtd dataContractServiceXtd;
	@Autowired
	private DataContractService dataContractService;
	@Autowired
	private DictEmployeeService dictEmployeeService;
	@Autowired
	private DataEmployeeachiRecordServiceXtd dataEmployeeachiRecordServiceXtd;
	@Autowired
	private DataContractpayDetailServiceXtd dataContractpayDetailServiceXtd;
	@Autowired
	private SysConfigService sysConfigService;
	@Autowired
	private DictWagesTypeServiceXtd dictWagesTypeServiceXtd;
	@Autowired
	private DictEmployeeServiceXtd dictEmployeeServiceXtd;
	@Autowired
	private DictJobServiceXtd dictJobServiceXtd;
	@Autowired
	private DataRecommendRecordServiceXtd dataRecommendRecordServiceXtd;
	@Autowired
	private DictDepartmentServiceXtd dictDepartmentServiceXtd;
	@Autowired
	private DataBigareaachiRecordServiceXtd dataBigareaachiRecordServiceXtd;
	@Autowired
	private DataDirectorachiRecordServiceXtd dataDirectorachiRecordServiceXtd;
	@Autowired
	private DataAreaachiRecordServiceXtd dataAreaachiRecordServiceXtd;
	@Autowired
	private DataPayrollServiceXtd dataPayrollServiceXtd;
	@Autowired
	private DataAddmoneyServiceXtd dataAddmoneyServiceXtd;
	@Autowired
	private DataDirectcheckServiceXtd dataDirectcheckServiceXtd;
	@Autowired
	private DataFormalcheckServiceXtd dataFormalcheckServiceXtd;
	@Autowired
	private DataBranchcheckServiceXtd dataBranchcheckServiceXtd;
	@Autowired
	private DataAreacheckServiceXtd dataAreacheckServiceXtd;
	@Autowired
	private DataBigareacheckServiceXtd dataBigareacheckServiceXtd;
	@Autowired
	private DataLostmoneyServiceXtd dataLostmoneyServiceXtd;
	@Autowired
	private DataPayrollDxdetailService dataPayrollDxdetailService;
	@Autowired
	private DataMonthdirectServiceXtd dataMonthdirectServiceXtd;
	@Autowired
	private DataRecommendServiceXtd dataRecommendServiceXtd;
	@Autowired
	private DataTeampayServiceImplXtd dataTeampayServiceImplXtd;
	@Autowired
	private DataPayrollDxdetailServiceXtd dataPayrollDxdetailServiceXtd;
	@Autowired
	private DataTeampayServiceXtd dataTeampayServiceXtd;
	@Autowired
	private DataContractDaoXtd dataContractDaoXtd;
	@Autowired
	private DataDxRecordService dataDxRecordService;
	@Autowired
	private DataCalculateKService dataCalculateKService;
	@Autowired
	private DataEmpPerformanceService dataEmpPerformanceService;
	@Autowired
	private HisDepartmentServiceXtd hisDepartmentServiceXtd;

	@RequestMapping("/datacontract.html")
	public String list(){
		return "datacontract/datacontract.html";
	}

	/**
	 * 列表
	 */
	@ResponseBody
	@RequestMapping("/list")
	@RequiresPermissions("datacontract:list")
	public R list(Integer page, Integer limit){
		Map<String, Object> map = new HashMap<>();
		map.put("offset", (page - 1) * limit);
		map.put("limit", limit);


		//查询列表数据
		List<DataContractEntity> dataContractList = dataContractService.queryList(map);
		int total = dataContractService.queryTotal(map);

		PageUtils pageUtil = new PageUtils(dataContractList, total, limit, page);

		return R.ok().put("page", pageUtil);
	}



	@ResponseBody
	@RequestMapping("/listXtd")
	@RequiresPermissions("datacontract:list")
	public R listXtd(Integer page, Integer limit,String sort,String order,String value,String calTime){
		Map<String, Object> map = new HashMap<>();
		map.put("offset", (page - 1) * limit);
		map.put("limit", limit);
		map.put("value", value);
		map.put("calTime", calTime);
		if (sort.isEmpty() || sort == null) {
			map.put("orderby", " order by contractDate desc,contractNo desc ");
		} else {
			map.put("orderby", " order by " + sort + " " + order + " ");
		}
		//查询列表数据
		List<DataContractEntityXtd> dataContractList = dataContractServiceXtd.queryListXtd(map);
		int total = dataContractServiceXtd.queryTotalXtd(map);

		PageUtils pageUtil = new PageUtils(dataContractList, total, limit, page);

		return R.ok().put("page", pageUtil);
	}


	/**
	 * 信息
	 */
	@ResponseBody
	@RequestMapping("/info/{id}")
	@RequiresPermissions("datacontract:info")
	public R info(@PathVariable("id") String id){
		DataContractEntity dataContract = dataContractService.queryObject(id);

		return R.ok().put("dataContract", dataContract);
	}



	@ResponseBody
	@RequestMapping("/infoXtd/{id}")
	public R infoXtd(@PathVariable("id") String id){
		/*Map<String, Object> map = new HashMap<>();
		map.put("offset", 0);
		map.put("limit", 1);
		map.put("id", id);*/
		DataContractEntityXtd dataContract = dataContractServiceXtd.queryObjectXtd(id);
		if (dataContract == null) {
			Map<String, Object> map = new HashMap<>();
			map.put("offset", 0);
			map.put("limit", 1);
			map.put("hisid", id);
			List<HisContractEntityXtd> hisContractXtd = hisContractServiceXtd.queryObjectXtd(map);
			map.put("contractid", id);
			List<HisContractpayEntityXtd> hisContractpayList = hisContractpayServiceXtd.queryListXtd(map);
			return R.ok().put("dataContract", hisContractXtd.get(0)).put("dataContractpayList", hisContractpayList);
		} else {
			Map<String, Object> mapa = new HashMap<>();
			mapa.put("contractid", id);
			List<DataContractpayEntityXtd> dataContractpayList = dataContractpayServiceXtd.queryListXtd(mapa);
			return R.ok().put("dataContract", dataContract).put("dataContractpayList", dataContractpayList);
		}
	}



	/**
	 * 保存
	 */
	@ResponseBody
	@RequestMapping("/save")
	@RequiresPermissions("datacontract:save")
	public R save(@RequestBody DataContractEntity dataContract){
		dataContractService.save(dataContract);

		return R.ok();
	}

	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("datacontract:update")
	public R update(@RequestBody DataContractEntity dataContract){
		dataContractService.update(dataContract);

		return R.ok();
	}

	/**
	 * 删除
	 */
	@ResponseBody
	@RequestMapping("/delete")
	@RequiresPermissions("datacontract:delete")
	public R delete(@RequestBody String[] ids){
		dataContractService.deleteBatch(ids);

		return R.ok();
	}

	/**
	 * 导入excel
	 * @throws Exception 
	 * @throws IOException 
	 */
	@ResponseBody
	@RequestMapping("/upload")
	public R upload(@RequestParam("file") MultipartFile multfile,String time) throws Exception{ 
		/*try {*/
		if(time==null || time.length()==0 || time.indexOf("-")<0){
			Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
					ShiroUtils.getUserEntity().getUsername(), "合同数据导入失败",
					"未选择数据时间", "");
			return R.error("请选择数据时间");
		}
		R resultR = ExcelUtils.textConExcel(multfile.getInputStream(),0);
		if (Integer.parseInt(resultR.get("code").toString())!=0) {
			Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
					ShiroUtils.getUserEntity().getUsername(), "合同数据导入失败",
					resultR.get("msg").toString(), time);
			return resultR;

		}
		Map<String, Object> mape=new HashMap<>();
		int total = dictDepartmentService.queryTotal(mape);
		if(total==0){
			Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
					ShiroUtils.getUserEntity().getUsername(), "合同数据导入失败",
					"未导入组织架构数据", time);
			return R.error("请先导入组织架构数据");
		}
		total = dictEmployeeService.queryTotal(mape);
		if(total==0){
			Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
					ShiroUtils.getUserEntity().getUsername(), "合同数据导入失败",
					"未导入员工数据", time);
			return R.error("请先导入员工数据");
		}
		Integer showType=0;
		Map<String, Object> map=new HashMap<>();
		map.put("year", Integer.parseInt(time.split("-")[0]));
		map.put("month", Integer.parseInt(time.split("-")[1]));
		total = hisEmployeeServiceXtd.queryTotalXtd(map);
		if (total>0) {
			Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
					ShiroUtils.getUserEntity().getUsername(), "合同数据导入失败",
					"已有历史数据，不可再导入", time);
			return R.error("已有历史数据，不可再导入");
		} else {
			if(Integer.valueOf(map.get("month").toString())==1){
				map.remove("year");
				map.put("year", Integer.parseInt(time.split("-")[0])-1);
				map.remove("month");
				map.put("month", 12);
			}else{
				map.remove("month");
				map.put("month", Integer.parseInt(time.split("-")[1])-1);
			}
			total = hisEmployeeServiceXtd.queryTotalXtd(map);
			Map<String, Object> hismap=new HashMap<>();
			int histotal = hisEmployeeServiceXtd.queryTotalXtd(hismap);
			if(total==0 && histotal!=0){
				Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
						ShiroUtils.getUserEntity().getUsername(), "合同数据导入失败",
						"请先将上个月数据转存历史，再导入", time);
				return R.error("请先将上个月数据转存历史，再导入");
			}
			Map<String, Object> mapb=new HashMap<>();
			mapb.put("year", time.split("-")[0]);
			mapb.put("month", time.split("-")[1]);
			total = dataContractpayServiceXtd.queryTotalXtd(mapb);
			if(total==0){
				showType=0;
			}else{
				showType=1;
			}
		}
		Map<String, Object> mapc = new HashMap<>();
		List<DataContractEntity> dataContractList = dataContractService.queryList(mapc);
		List<List<Object>> list = ExcelUtils.readExcel2(multfile.getInputStream(),0);
		//导入excel的数据
		List<Map<String,Object>> contracts = AssignUtils.assignToContractNewUuid(list);
		//生成要保存到data_contract表的数据
		List<Map<String,Object>> contracts1 = contractListUseSave(contracts);

		if (dataContractList==null || dataContractList.size()==0) {

		}else{

			if (contracts==null || contracts.size()==0) {

			} else {
				for(int n=0;n<contracts1.size();n++){
					Map<String, Object> mapd = contracts1.get(n);
					for(int m=0;m<dataContractList.size();m++){
						if(dataContractList.get(m).getContractno().equals(mapd.get("contractno"))){

							contracts1.get(n).remove("id");
							contracts1.get(n).put("id", dataContractList.get(m).getId());
							break;
						}
					}
				}
			}
		}
		List<Map<String,Object>> contractsXtd = contractXtdListUseSave(contracts1,time);
		if (contractsXtd==null || contractsXtd.size()==0) {
			/*dataContractXtdServiceXtd.deleteAll();*/
		}else{
			/*dataContractXtdServiceXtd.deleteAll();*/
			dataContractXtdServiceXtd.saveBatchXtd(contractsXtd);
		}
		//生成要保存到data_contractpay表的数据
		List<Map<String,Object>> contracts2 = contractPayListUseSave(contracts1);
		//生成要保存到data_contractpay_detail表的数据
		List<Map<String,Object>> contracts3 = contractPayDetListUseSave(contracts2,time);
		/*if(contracts3.size()!=0) {
			String reamrk = (String)contracts3.get(0).get("error");
			if(reamrk!=null) {
				return R.error(reamrk);
			}
		}*/
		//查找是否原有此年月的数据
		Map<String, Object> mapf = new HashMap<>();
		mapf.put("year", time.split("-")[0]);
		mapf.put("month", time.split("-")[1]);
		total = dataContractpayServiceXtd.queryTotalXtd(mapf);
		if(total>0){
			dataContractpayServiceXtd.deleteXtd(mapf);
		}
		total = dataContractpayDetailServiceXtd.queryTotalXtd(mapf);
		if(total>0){
			dataContractpayDetailServiceXtd.deleteXtd(mapf);
		}
		total=dataContractServiceXtd.queryTotalXtdByMonth(mapf);
		if(total>0){
			dataContractServiceXtd.deleteXtdByMonth(mapf);
		}
		if (dataContractList==null || dataContractList.size()==0) {
			dataContractServiceXtd.impExcelInList(contracts1);
			dataContractpayServiceXtd.impExcelInList(contracts2);
			dataContractpayDetailServiceXtd.impExcelInList(contracts3);
			Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
					ShiroUtils.getUserEntity().getUsername(), "合同数据导入成功",
					"", time);
			return R.ok();	
		}else{

			if (contracts==null || contracts.size()==0) {

				dataContractServiceXtd.impExcelInList(contracts1);
				dataContractpayServiceXtd.impExcelInList(contracts2);
				dataContractpayDetailServiceXtd.impExcelInList(contracts3);
				Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
						ShiroUtils.getUserEntity().getUsername(), "合同数据导入成功",
						"", time);
				return R.ok();
			} else {
				String[] deleteid=new String[contracts1.size()];
				for(int n=0;n<contracts1.size();n++){
					Map<String, Object> mapd = contracts1.get(n);
					for(int m=0;m<dataContractList.size();m++){
						if(dataContractList.get(m).getContractno().equals(mapd.get("contractno"))){
							deleteid[n]=dataContractList.get(m).getId();
							/*contracts1.get(n).remove("id");
                    			contracts1.get(n).put("id", dataContractList.get(m).getId());*/
							break;
						}
					}
				}
				dataContractService.deleteBatch(deleteid);
				dataContractServiceXtd.impExcelInList(contracts1);
				dataContractpayServiceXtd.impExcelInList(contracts2);
				dataContractpayDetailServiceXtd.impExcelInList(contracts3);
				Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
						ShiroUtils.getUserEntity().getUsername(), "合同数据导入成功",
						"", time);
				return R.ok();	
			}
		}
		/*} catch (Exception e) {
			Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
        			ShiroUtils.getUserEntity().getUsername(), "合同数据导入失败",
        			"导入失败", time);
			return R.error("导入失败");
		}*/

	}
	/**
	 * 计算控制层
	 * @throws ParseException 
	 * 
	 */
	@ResponseBody
	@RequestMapping(value="/calculate",method=RequestMethod.POST)	

	public String calculate(String time,String days) throws ParseException{		
		Map<String, Object> map=new HashMap<>();
		BigDecimal day=new BigDecimal(days);
		CalculateUtils.calculate(time,day,dataCalculateKService,dataContractServiceXtd,dataDxRecordService,dataContractDaoXtd,dataRecommendServiceXtd, dataMonthdirectServiceXtd,dataBigareaachiRecordServiceXtd, dictDepartmentServiceXtd, dataBranchachiRecordServiceXtd, dataRecommendRecordServiceXtd, dictEmployeeService, dataEmployeeachiRecordServiceXtd, dataContractpayDetailServiceXtd, sysConfigService, dictWagesTypeServiceXtd, dictEmployeeServiceXtd, dictJobServiceXtd, dataDirectorachiRecordServiceXtd, dataAreaachiRecordServiceXtd, dataPayrollServiceXtd, hisEmployeeServiceXtd, dataContractXtdServiceXtd, dataPayrollDxdetailService,dataAddmoneyServiceXtd,dataLostmoneyServiceXtd,dataEmpPerformanceService,hisDepartmentServiceXtd);
		/*CalculateUtils.saveformalInfo(time, dataFormalcheckServiceXtd, dictEmployeeServiceXtd, dataContractpayDetailServiceXtd);
		CalculateUtils.saveZGcheck(time, dictDepartmentServiceXtd, dataContractpayDetailServiceXtd, dictEmployeeServiceXtd, hisEmployeeServiceXtd, dataDirectcheckServiceXtd);
		CalculateUtils.saveFHcheck(time, dictDepartmentServiceXtd,dataContractpayDetailServiceXtd, dictEmployeeServiceXtd, hisEmployeeServiceXtd, dataDirectcheckServiceXtd, dataBranchcheckServiceXtd);
		CalculateUtils.saveQYcheck(time, dictDepartmentServiceXtd,dataContractpayDetailServiceXtd, dictEmployeeServiceXtd, hisEmployeeServiceXtd, dataDirectcheckServiceXtd, dataAreacheckServiceXtd);
		CalculateUtils.saveDQcheck(time, dictDepartmentServiceXtd,dataContractpayDetailServiceXtd, dictEmployeeServiceXtd, hisEmployeeServiceXtd, dataDirectcheckServiceXtd, dataBigareacheckServiceXtd);
		CalculateUtils.saveFHcost(time, dataTeampayServiceImplXtd, dataRecommendServiceXtd, dataContractpayDetailServiceXtd, dataMonthdirectServiceXtd, sysConfigService, dictEmployeeServiceXtd, dictDepartmentServiceXtd, dataPayrollServiceXtd);*/
		Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
				ShiroUtils.getUserEntity().getUsername(), "计算工资成功",
				"", time);
		map.put("result", "计算完成");
		String mapJson = JSON.toJSONString(map);
		return mapJson;
	}

	/**
	 * 
	 * @author Murphy Wu
	 * 创建时间：2018年6月8日 上午9:23:59 
	 * 说明 :把excel中的数据转换成能直接保存到contract表的数据
	 */
	public List<Map<String,Object>> contractListUseSave(List<Map<String,Object>> list){
		if (list==null || list.size()==0) {
			return list;
		}
		List<Map<String,Object>> contracts = new ArrayList<Map<String,Object>>();
		Map<String, Object> map = new HashMap<>();
		List<DictEmployeeEntityXtd> dictEmployeeList = dictEmployeeServiceXtd.queryListXtd(map);
		if(dictEmployeeList==null || dictEmployeeList.size()==0){
			return contracts;
		}
		String emp="";
		String empDan="";
		String empZhu="";
		for (Map<String, Object> contract : list) {
			/*contract.remove("thismonthpaidmoney");
			contract.remove("paydate");*/
			contract.put("createtime", new Date());
			contract.put("createby", ShiroUtils.getUserEntity().getUsername());
			contract.put("state", 1);
			emp=contract.get("employeeid").toString();
			if (contract.get("splitemployeeidlist").toString().indexOf(",")>-1) {
				empZhu=contract.get("splitemployeeidlist").toString();
			} else {
				empDan=contract.get("splitemployeeidlist").toString();
			}
			String[] zu=new String[empZhu.split(",").length];
			String[] depZu=new String[empZhu.split(",").length];
			contract.remove("employeeid");
			contract.remove("splitemployeeidlist");
			for(int i=0;i<dictEmployeeList.size();i++){
				if (empDan.length()>0) {
					if (contract.get("employeeid")==null) {
						if(dictEmployeeList.get(i).getWorkno().equals(emp)){
							contract.put("employeeid", dictEmployeeList.get(i).getId());
						}else{
							if(i+1==dictEmployeeList.size()){
								contract.put("employeeid", "");
							}
						}
					} else {}
					if (contract.get("splitemployeeidlist")==null) {
						if(dictEmployeeList.get(i).getWorkno().equals(empDan)){
							contract.put("splitemployeeidlist", dictEmployeeList.get(i).getId());
							contract.put("depListZu", dictEmployeeList.get(i).getDeptno());
						}else{
							if(i+1==dictEmployeeList.size()){
								contract.put("splitemployeeidlist", "");
								contract.put("depListZu", "");
							}
						}
					} else {}


				} else {
					if (contract.get("employeeid")==null) {
						if(dictEmployeeList.get(i).getWorkno().equals(emp)){
							contract.put("employeeid", dictEmployeeList.get(i).getId());
						}else{
							if(i+1==dictEmployeeList.size()){
								contract.put("employeeid", "");
							}
						}
					} else {}
					if (contract.get("splitemployeeidlist")==null) {
						for(int n=0;n<zu.length;n++){

							if(zu[n] !=null && zu[n].length()>0){continue;}
							if(dictEmployeeList.get(i).getWorkno().equals(empZhu.split(",")[n])){
								zu[n]=dictEmployeeList.get(i).getId();
								depZu[n]=dictEmployeeList.get(i).getDeptno();
							}else{

							}

						}
						int a=0;
						for(int m=0;m<zu.length;m++){
							if(zu[m] !=null && zu[m].length()>0){a=a+1;continue;}
						}
						if (a==zu.length) {
							contract.put("splitemployeeidlist", StringUtils.join(zu, ","));
							contract.put("depListZu", StringUtils.join(depZu, ","));
						}
					} else {}



				}

				if(contract.get("employeeid")!=null && contract.get("splitemployeeidlist")!=null){
					/*contracts.add(contract);
					emp="";
					empDan="";
					empZhu="";*/
					break;
				}
			}

			contracts.add(contract);
			emp="";
			empDan="";
			empZhu="";
		}
		return contracts;
	}

	/**
	 * 
	 * @author Murphy Wu
	 * 创建时间：2018年6月8日 下午4:01:17 
	 * 说明 :把数据转换成能直接保存到data_contractpay表的数据
	 */
	public List<Map<String,Object>> contractPayListUseSave(List<Map<String,Object>> list){
		if (list==null || list.size()==0) {
			return list;
		}
		List<Map<String,Object>> contracts = new ArrayList<Map<String,Object>>();
		Map<String, Object> contract = null;
		for (Map<String,Object> list2 : list) {
			String iddata=Common.getUUID().split(",")[1];
			BigDecimal shouldmoney=new BigDecimal(list2.get("thismonthpaidmoney").toString())
					.add(new BigDecimal(list2.get("nopaidmoney").toString()));
			contract = new HashMap<String,Object>();
			contract.put("id",iddata);
			contract.put("contractid", list2.get("id"));
			contract.put("paytime", list2.get("paydate"));
			contract.put("shouldmoney", shouldmoney);
			contract.put("paidmoney", list2.get("thismonthpaidmoney"));
			contract.put("createtime",  new Date());
			contract.put("createby",  ShiroUtils.getUserEntity().getUsername());
			contract.put("state",1);

			contract.put("splitemployeeidlist", list2.get("splitemployeeidlist"));
			contract.put("depListZu", list2.get("depListZu"));
			contract.put("splitpercent", list2.get("splitpercent"));
			contracts.add(contract);
		}
		return contracts;
	}

	/**
	 * 
	 * @author Murphy Wu
	 * 创建时间：2018年6月8日 下午4:02:19 
	 * 说明 :把数据转换成能直接保存到data_contractpay_detail表的数据
	 */
	public List<Map<String,Object>> contractPayDetListUseSave(List<Map<String,Object>> list,String time){
		if (list==null || list.size()==0) {
			return list;
		}
		//查询当前所有部门数据
		Map<String, Object> map = new HashMap<>();
		List<DictDepartmentEntity> dictDepartmentList = dictDepartmentService.queryList(map);
		//定义一个集合，用于装所有部门的编号
		List<Map<String,Object>> depNoList = new ArrayList<Map<String,Object>>();
		Map<String, Object> depNoDetil = null;
		if (dictDepartmentList == null || dictDepartmentList.size()==0) {
			return list;
		} else {
			//开始遍历装编号
			for (DictDepartmentEntity entity : dictDepartmentList) {
				depNoDetil = new HashMap<String,Object>();
				depNoDetil.put("deptno",entity.getDeptNo());
				depNoList.add(depNoDetil);

			}
		}
		//根据各自部门编号查找他的所有上级关系
		List<DictDepartmentEntityXtd> result = dictDepartmentServiceXtd.queryDepCengList(depNoList);
		if (result == null || result.size()==0) {
			return list;
		}
		//定义一个集合，用于存储和返回此函数的结果值
		List<Map<String,Object>> contracts = new ArrayList<Map<String,Object>>();
		Map<String, Object> contract = null;
		for (Map<String,Object> list2 : list) {
			System.out.println(list2.get("contractid").toString());
			System.out.println(list2.get("paidmoney").toString());
			
			if(list2.get("splitemployeeidlist")==null) {
				System.out.println(11222);
			}
			if (list2.get("splitemployeeidlist").toString().indexOf(",")>-1) {
				String[] people=list2.get("splitemployeeidlist").toString().split(",");//取出员工id
				String[] depNoZu=list2.get("depListZu").toString().split(",");//取出员工组编号
				String[] biliMoney=list2.get("splitpercent").toString().split(",");
				for(int i=0;i<people.length;i++){
					String iddata=Common.getUUID().split(",")[1];
					BigDecimal shouldmoney=new BigDecimal(list2.get("paidmoney").toString())
							.multiply(new BigDecimal(biliMoney[i].toString()));
					String depStr="";
					//处理上级关系
					for(int z=0;z<result.size();z++){
						if (depNoZu[i].equals(result.get(z).getDeptNo())) {//找到对应关系
							depStr=result.get(z).getExcol();//此部门所有上级关系
							break;
						}
					}
					Map<String,Object> contract1 = new HashMap<String,Object>();
					if (depStr.length()==0) {
						contract1.put("directorno",null);
						contract1.put("branchno",null);
						contract1.put("areano",null);
						contract1.put("bigareano",null);
					} else {
						if (depStr.indexOf(",")<0) {
							//若上级关系只有一个
							contract1.put("directorno",depStr);
							contract1.put("branchno",depStr);
							contract1.put("areano",depStr);
							contract1.put("bigareano",depStr);
						} else {
							String[] str=new String[4];
							if (depStr.split(",").length==2) {
								//若上级有2个
								contract1.put("directorno",depStr.split(",")[1]);
								contract1.put("branchno",depStr.split(",")[1]);
								contract1.put("areano",depStr.split(",")[1]);
								contract1.put("bigareano",depStr.split(",")[1]);
							} else if(depStr.split(",").length==3){
								//若上级有3个
								contract1.put("directorno",depStr.split(",")[2]);
								contract1.put("branchno",depStr.split(",")[2]);
								contract1.put("areano",depStr.split(",")[2]);
								contract1.put("bigareano",depStr.split(",")[2]);
							} else if(depStr.split(",").length==4){
								//若上级有4个
								contract1.put("directorno",depStr.split(",")[3]);
								contract1.put("branchno",depStr.split(",")[3]);
								contract1.put("areano",depStr.split(",")[3]);
								contract1.put("bigareano",depStr.split(",")[2]);
							} else if(depStr.split(",").length==5){
								//若上级有5个
								contract1.put("directorno",depStr.split(",")[4]);
								contract1.put("branchno",depStr.split(",")[4]);
								contract1.put("areano",depStr.split(",")[3]);
								contract1.put("bigareano",depStr.split(",")[2]);
							} else if(depStr.split(",").length==6){
								//若上级有6个
								contract1.put("directorno",depStr.split(",")[5]);
								contract1.put("branchno",depStr.split(",")[4]);
								contract1.put("areano",depStr.split(",")[3]);
								contract1.put("bigareano",depStr.split(",")[2]);
							}else{
								contract1.put("directorno",depStr.split(",")[5]);
								contract1.put("branchno",depStr.split(",")[4]);
								contract1.put("areano",depStr.split(",")[3]);
								contract1.put("bigareano",depStr.split(",")[2]);
							}

						}
					}
					contract1.put("id",iddata);
					contract1.put("contractid", list2.get("contractid"));
					contract1.put("paytime", list2.get("paytime"));
					contract1.put("contractpayid", list2.get("id"));
					contract1.put("splitmoney", shouldmoney);
					contract1.put("employeeid", people[i]);
					contract1.put("createtime",  new Date());
					contract1.put("createby",  ShiroUtils.getUserEntity().getUsername());
					contract1.put("state",1);
					//如果有记录要选最老记录的组织架构
					Map<String, Object> queryMap=new HashMap<>();
					queryMap.put("contractID", list2.get("contractid"));
					queryMap.put("employeeID", people[i]);
					queryMap.put("month", time);
					//排除当前月月份
					List<DataContractpayDetailEntityXtd> record = dataContractpayDetailServiceXtd.getRecord(queryMap);
					if(record!=null&&record.size()!=0) {
						DataContractpayDetailEntityXtd dataContractpayDetailEntityXtd = record.get(0);
						String areaNo = dataContractpayDetailEntityXtd.getAreaNo();
						String bigAreaNo = dataContractpayDetailEntityXtd.getBigAreaNo();
						String branchNo = dataContractpayDetailEntityXtd.getBranchNo();
						String directorNo = dataContractpayDetailEntityXtd.getDirectorNo();
						contract1.put("directorno",directorNo);
						contract1.put("branchno",branchNo);
						contract1.put("areano",areaNo);
						contract1.put("bigareano",bigAreaNo);
					}
					contracts.add(contract1);
				}
			} else {
				String iddata=Common.getUUID().split(",")[1];
				String depStr=list2.get("depListZu").toString();
				for(int z=0;z<result.size();z++){
					if (depStr.equals(result.get(z).getDeptNo())) {
						depStr=result.get(z).getExcol();
						break;
					}
					if (z+1==result.size()) {
						depStr="";
					}
				}
				Map<String,Object> contract1 = new HashMap<String,Object>();
				if (depStr.length()==0) {
					contract1.put("directorno",null);
					contract1.put("branchno",null);
					contract1.put("areano",null);
					contract1.put("bigareano",null);
				} else {
					if (depStr.indexOf(",")<0) {
						contract1.put("directorno",depStr);
						contract1.put("branchno",depStr);
						contract1.put("areano",depStr);
						contract1.put("bigareano",depStr);
					} else {
						String[] str=new String[4];
						if (depStr.split(",").length==2) {
							contract1.put("directorno",depStr.split(",")[1]);
							contract1.put("branchno",depStr.split(",")[1]);
							contract1.put("areano",depStr.split(",")[1]);
							contract1.put("bigareano",depStr.split(",")[1]);
						} else if(depStr.split(",").length==3){
							contract1.put("directorno",depStr.split(",")[2]);
							contract1.put("branchno",depStr.split(",")[2]);
							contract1.put("areano",depStr.split(",")[2]);
							contract1.put("bigareano",depStr.split(",")[2]);
						} else if(depStr.split(",").length==4){
							contract1.put("directorno",depStr.split(",")[3]);
							contract1.put("branchno",depStr.split(",")[3]);
							contract1.put("areano",depStr.split(",")[3]);
							contract1.put("bigareano",depStr.split(",")[2]);
						} else if(depStr.split(",").length==5){
							contract1.put("directorno",depStr.split(",")[4]);
							contract1.put("branchno",depStr.split(",")[4]);
							contract1.put("areano",depStr.split(",")[3]);
							contract1.put("bigareano",depStr.split(",")[2]);
						} else if(depStr.split(",").length==6){
							contract1.put("directorno",depStr.split(",")[5]);
							contract1.put("branchno",depStr.split(",")[4]);
							contract1.put("areano",depStr.split(",")[3]);
							contract1.put("bigareano",depStr.split(",")[2]);
						}else{
							contract1.put("directorno",depStr.split(",")[5]);
							contract1.put("branchno",depStr.split(",")[4]);
							contract1.put("areano",depStr.split(",")[3]);
							contract1.put("bigareano",depStr.split(",")[2]);
						}

					}
				}
				BigDecimal shouldmoney=new BigDecimal(list2.get("paidmoney").toString())
						.multiply(new BigDecimal(list2.get("splitpercent").toString()));
				//contract1 = new HashMap<String,Object>();
				contract1.put("id",iddata);
				contract1.put("contractid", list2.get("contractid"));
				contract1.put("paytime", list2.get("paytime"));
				contract1.put("contractpayid", list2.get("id"));
				contract1.put("splitmoney", shouldmoney);
				contract1.put("employeeid", list2.get("splitemployeeidlist"));
				contract1.put("createtime",  new Date());
				contract1.put("createby",  ShiroUtils.getUserEntity().getUsername());
				contract1.put("state",1);
				//如果有记录要选最老记录的组织架构
				Map<String, Object> queryMap=new HashMap<>();
				queryMap.put("contractID", list2.get("contractid"));
				queryMap.put("employeeID",list2.get("splitemployeeidlist"));
				queryMap.put("month", time);
				List<DataContractpayDetailEntityXtd> record = dataContractpayDetailServiceXtd.getRecord(queryMap);
				if(record!=null&&record.size()!=0) {
					DataContractpayDetailEntityXtd dataContractpayDetailEntityXtd = record.get(0);
					String areaNo = dataContractpayDetailEntityXtd.getAreaNo();
					String bigAreaNo = dataContractpayDetailEntityXtd.getBigAreaNo();
					String branchNo = dataContractpayDetailEntityXtd.getBranchNo();
					String directorNo = dataContractpayDetailEntityXtd.getDirectorNo();
					contract1.put("directorno",directorNo);
					contract1.put("branchno",branchNo);
					contract1.put("areano",areaNo);
					contract1.put("bigareano",bigAreaNo);
				}
				contracts.add(contract1);
			}

		}
		return contracts;
	}


	/**
	 * 
	 * @author Murphy Wu
	 * 创建时间：2018年6月19日 下午3:54:25 
	 * 说明 :把数据转换成能直接保存到contractXtd表的数据
	 */
	public List<Map<String,Object>> contractXtdListUseSave(List<Map<String,Object>> list,String month){
		//如果存在该合同，在插入数据时应该去除这些数据，这些数据已存在于数据库，并且出了要存为历史之外不需要进行任何操作
		List<String> allContractNo = dataContractServiceXtd.getAllContractNo();
		if (list==null || list.size()==0) {
			return list;
		}
		List<Map<String,Object>> contracts = new ArrayList<Map<String,Object>>();
		Map<String, Object> contract = null;
		for (Map<String,Object> list2 : list) {
			if (list2.get("haspaidmoney").toString().equals(list2.get("thismonthpaidmoney").toString())) {				
				if(allContractNo.contains(list2.get("contractno").toString())) {
					continue;
				}
				System.out.println(list2.get("contractid"));
				if (list2.get("splitemployeeidlist").toString().indexOf(",")>-1) {
					String[] people=list2.get("splitemployeeidlist").toString().split(",");
					String[] everyoneNo=list2.get("everyoneNo").toString().split(",");
					String[] biliMoney=list2.get("splitpercent").toString().split(",");
					for(int i=0;i<people.length;i++){
						String iddata=Common.getUUID().split(",")[1];
						BigDecimal shouldmoney=new BigDecimal(list2.get("contractmoney").toString())
								.multiply(new BigDecimal(biliMoney[i].toString()));
						contract = new HashMap<String,Object>();
						contract.put("id",iddata);
						contract.put("employeeid", people[i]);
						contract.put("contractid", list2.get("id"));
						contract.put("shouldmoney", shouldmoney);
						contract.put("everyoneno", everyoneNo[i]);
						contract.put("createtime",  new Date());
						contract.put("createby",  ShiroUtils.getUserEntity().getUsername());
						contract.put("excol",list2.get("contractmonth"));
						contracts.add(contract);
					}
				}else{
					String iddata=Common.getUUID().split(",")[1];
					BigDecimal shouldmoney=new BigDecimal(list2.get("contractmoney").toString())
							.multiply(new BigDecimal(list2.get("splitpercent").toString()));
					contract = new HashMap<String,Object>();
					contract.put("id",iddata);
					contract.put("employeeid", list2.get("splitemployeeidlist"));
					contract.put("contractid", list2.get("id"));
					contract.put("shouldmoney", shouldmoney);
					contract.put("everyoneno", list2.get("everyoneNo"));
					contract.put("createtime",  new Date());
					contract.put("createby",  ShiroUtils.getUserEntity().getUsername());
					contract.put("excol",list2.get("contractmonth"));
					contracts.add(contract);
				}
			}

		}
		return contracts;
	}
	/**
	 * @throws ParseException 
	 * 
	 */
	@ResponseBody
	@RequestMapping("/cancel/{time}")	

	public String cancel(@PathVariable("time") String time) throws ParseException{		
		Map<String, Object> map=new HashMap<>();
		DataPayrollEntity newRecord = dataPayrollServiceXtd.getNewRecord();
		if(newRecord==null) {
			map.put("result", "没有需要撤销的月份");
		}else {
			String payrollmonth = newRecord.getPayrollmonth();
			if(payrollmonth.equals(time)) {
				CalculateUtils.cancelCal(time,dataCalculateKService,dataDxRecordService,dataTeampayServiceXtd,dataPayrollDxdetailServiceXtd,dataMonthdirectServiceXtd,dataRecommendServiceXtd, dataAreaachiRecordServiceXtd, dataAreacheckServiceXtd, dataBigareaachiRecordServiceXtd, dataBigareacheckServiceXtd, dataBranchachiRecordServiceXtd, dataBranchcheckServiceXtd, dataDirectcheckServiceXtd, dataDirectorachiRecordServiceXtd, dataEmployeeachiRecordServiceXtd, dataFormalcheckServiceXtd, dataPayrollServiceXtd, dataRecommendRecordServiceXtd);
				Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,

						ShiroUtils.getUserEntity().getUsername(), "撤销计算成功",
						"", time);
				map.put("result", "撤销完成");
			}else {
				map.put("result", "请先撤销之前的月份");
			}
		}	
		String mapJson = JSON.toJSONString(map);
		return mapJson;
	}
	/**
	 * @throws ParseException 
	 * 
	 */
	/*	@ResponseBody
	@RequestMapping("/deleteHis")	

	public String deleteHis() throws ParseException{		
		Map<String, Object> map=new HashMap<>();
		hisContractServiceXtd.deleteXtd1();
		hisContractServiceXtd.deleteXtd2();
		hisContractServiceXtd.deleteXtd3();
		hisContractServiceXtd.deleteXtd4();
		hisContractServiceXtd.deleteXtd5();
		hisContractServiceXtd.deleteXtd6();
		map.put("result", "删除历史纪录完成");
		String mapJson = JSON.toJSONString(map);
		return mapJson;
	}*/

}
